package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 视频服务接口实现类
 */
@DubboService
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发布小视频
     *
     * @param video
     */
    @Override
    public void add(Video video) {
        video.setVid(idWorker.getNextId("video"));//推荐系统要使用到的vid(动态表中pid是一样)
        video.setCreated(System.currentTimeMillis());//发布视频的时间
        video.setText("写死的视频相关文字描述");
        mongoTemplate.insert(video);
    }

    /**
     * 推荐小视频分页查询
     *
     * @return
     */
    @Override
    public PageResult<Video> findPageVideo(Long page, Long pageSize) {
        long start = (page-1)*pageSize;//从那条开始查询 （page-1）*pageSize
        //1.查询总记录数
        Query query = new Query();
        long count = mongoTemplate.count(query, Video.class);
        //2.每页展示的数据
        query.skip(start).limit(pageSize.intValue());
        //2.1根据created排序
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return new PageResult<>(page,pageSize,count,videoList);
    }

    /**
     * 根据vid查询当前页面数据
     *
     * @param vidList
     * @return
     */
    @Override
    public PageResult<Video> findPageVideoByVids(List<Long> vidList) {
        Query query = new Query();
        query.addCriteria(Criteria.where("vid").in(vidList));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return new PageResult<>(1l,10l,10l,videoList);
    }

    /**
     * 查询指定用户发布的视频列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long page, Long pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").in(userId));
        long count = mongoTemplate.count(query, Video.class);
        query.limit(pagesize.intValue()).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }
}
